<template>
  <Upload
    :action="action"
    :show-upload-list="showUploadList"
    :type="type"
    :headers="headers"
    :format="format"
    :on-format-error="handleFormatError"
    :max-size="maxSize"
    :on-success="onSuccess"
    :on-progress="onProgress"
    :on-remove="onRemove"
    :before-upload="handleBeforeUpload"
    :on-error="onErrorFn"
    :on-exceeded-size="handleMaxSize"
  >
    <Button icon="ios-cloud-upload-outline">点击上传</Button>
  </Upload>
</template>
<script>
const getKeyValue = function(field, fieldData) {
  var data = field && field.indexOf(".") > -1 ? field.split(".") : [field];

  function extend(pName, o) {
    var val = o[pName];

    if (
      val &&
      typeof val === "string" &&
      val.indexOf("{") > -1 &&
      val.indexOf("}") > -1
    ) {
      try {
        o[pName] = JSON.parse(val);
      } catch (e) {
        o[pName] = val;
      }
    }
    // 如果还有长度继续遍历
    if (typeof val !== "undefined" && data.length) {
      return extend(data.shift(), val);
    }
    return val;
  }
  return extend(data.shift(), fieldData);
};
export default {
  name: "upload",
  data() {
    return {
      videoLink: "",
      videoList: [],
    };
  },
  props: {
    name: {
      //上传文件字段名
      default: "file"
    },
    limit: {
      default: "none"
    },
    action: {
      require: true,
      //后台上传地址
      default: "http://localhost:8090/uploadMock"
    },
    showUploadList: {
      //显示上传文件列表
      type: Boolean,
      default: true
    }, 
     // 文件格式
    format: {
      type: Array,
      default() {
        return ["mp4", "flv", "ogg"];
      }
    },
    type: {
      // 文件上传个数类型
      type: String,
      default: "select"
    },
    headers: {
      // header里面的信息
      type: Object
    },
    maxSize: {
      // 文件最大值
      type: [Number, String],
      default: 20 * 1024 * 1024
    },
    onError: {
      // 报错方法
      type: Function,
      default() {
        return this.$Notice.warning({
          title: "上传错误，请稍后重新上传"
        });
      }
    },
    beforeUpload: {
      // 上传前的操作
      type: Function,
      default() {
        return {};
      }
    },
    fieldData: {
      default: ""
    },
    fieldPath: {
      //配置后台的返回地址
      default: "path"
    },
    fieldId: {
      //配置后台返回的id
      default: "id"
    }
  },
  methods: {
    init() {
      this.videoList = [];
      this.dialogVisible = true;
    },
    addVideoLink() {
      if (this.videoLink && this.videoLink.indexOf("http") < 0) {
        this.$Message.warning("请输入正确的视频链接地址");
        return;
      }
      let videoList =
        this.videoLink.length > 0
          ? this.videoList.concat([{ id: "", path: this.videoLink }])
          : this.videoList;

      if (videoList && videoList.length == 0) {
        this.$Message.warning("请先添加视频");
        return;
      }
      this.videoList =
        this.videoLink.length > 0
          ? this.videoList.concat([{ id: "", path: this.videoLink }])
          : this.videoList;

      this.dialogVisible = false;
      this.$emit("emitVideoInfo", this.videoList);
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件大小限制提醒",
        desc:
          "文件  " +
          file.name +
          `太大了, 不能超过 ${Math.ceil(this.maxSize / 1024 / 1024)}M.`
      });
    },
    onSuccess(response, file, fileList) {
      let _response = "";
      if (this.fieldData.length > 0) {
        _response = getKeyValue(this.fieldData, response);
      } else {
        _response = response;
      }
      this.videoList.push({
        id: _response[this.fieldId] || "",
        path: _response[this.fieldPath]
      });
      this.$emit("on-success", { response, file, fileList });
    },
    onRemove(file, fileList) {
      this.videoList = this.videoList.filter(({ path }) => {
        return file.response[this.fieldPath] != path;
      });
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式不正确",
        desc: `文件${file.name}不准确，应该为${this.format}`
      });
    },
    onProgress(event, file, fileList) {},
    handleBeforeUpload() {
      const check = this.limit == "none" || this.videoList.length < this.limit;
      if (!check) {
        this.$Notice.warning({
          title: `文件个数不能超过${this.limit}个`
        });
      }
      return check;
    },
    onErrorFn(error, file, fileList) {
      this.onError(error, file, fileList);
    }
  }
};
</script>